package com.ruoyi.web.task;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.sts.domain.EventNotificationAlert;
import com.ruoyi.sts.domain.StsDataDetail;
import com.ruoyi.sts.domain.StsDataSyn;
import com.ruoyi.sts.domain.StsDevice;
import com.ruoyi.sts.service.IStsDataDetailService;
import com.ruoyi.sts.service.IStsDataSynService;
import com.ruoyi.sts.service.IStsDeviceService;
import com.ruoyi.system.domain.SysMsg;
import com.ruoyi.system.service.ISysMsgService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("stsTask")
public class StsTask {
    private static final Logger log = LoggerFactory.getLogger(StsTask.class);

    @Autowired
    private IStsDataSynService stsDataSynService;
    @Autowired
    private IStsDataDetailService stsDataDetailService;
    @Autowired
    private IStsDeviceService stsDeviceService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysMsgService sysMsgService;

    public void synStsData(){
        do {
            List<StsDataSyn> stsDataSyns = getStsDataSyn(1);
            if(CollectionUtils.isEmpty(stsDataSyns)){
                break;
            }

            for(StsDataSyn stsDataSyn:stsDataSyns){
                try {
                    JAXBContext context = JAXBContext.newInstance(EventNotificationAlert.class);
                    Unmarshaller unmarshaller = context.createUnmarshaller();
                    String regex = "\\sxmlns=\"[^\"]+\"\\s*";
                    String xml = stsDataSyn.getData().replaceAll(regex, "");
                    EventNotificationAlert eventNotificationAlert = (EventNotificationAlert)unmarshaller.unmarshal(new StringReader(xml));


                    R<StsDataDetail> r = stsDataDetailService.synData(eventNotificationAlert);
                    stsDataSyn.setSynTime(new Date());
                    if(r.getCode() == 0){
                        stsDataSyn.setSynFlag("Y");
                        stsDataSyn.setSynMsg("");
                    }else {
                        stsDataSyn.setSynFlag("N");
                        stsDataSyn.setSynMsg(r.getMsg());
                        stsDataSyn.setSynNum(stsDataSyn.getSynNum() + 1);
                    }

                }catch (Exception e){
                    log.error(e.getMessage(), e);
                    stsDataSyn.setSynFlag("N");
                    stsDataSyn.setSynMsg("数据异常：" + e.getMessage());
                    stsDataSyn.setSynNum(stsDataSyn.getSynNum() + 1);
                }finally {
                    stsDataSyn.setData(null);
                    stsDataSynService.updateStsDataSyn(stsDataSyn);
                }


            }
        }while (true);

    }

    private List<StsDataSyn> getStsDataSyn(Integer pageNum){
        PageHelper.startPage(pageNum, 100);
        return stsDataSynService.selectStsDataNoSynList();
    }

    public void sendStsDeviceMsg(){
        List<StsDevice> stsDevices = stsDeviceService.selectStsDeviceByLastSendTime();
        for(StsDevice stsDevice:stsDevices){
            try {
                if("0".equals(stsDevice.getStatus())){
                    String lastSendTime = stsDevice.getLastSendTime() == null?"新接入设备":DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", stsDevice.getLastSendTime());
                    List<SysUser> sysUsers = sysUserService.selectDeptAdmin(stsDevice.getDeptId1());
                    for(SysUser sysUser: sysUsers){
                        stsDevice.setStatus("0");
                        SysMsg sysMsg = new SysMsg();
                        sysMsg.setType("2");
                        sysMsg.setTitle(String.format("%s 设备离线了,识别码:%s", stsDevice.getName(), stsDevice.getIdCode()));
                        sysMsg.setContent(String.format("场所：%s，设备：%s，识别码：%s，超过了1小时未收到数据上传，上一次上传时间在：%s",
                                stsDevice.getDeptName2(), stsDevice.getName(), stsDevice.getIdCode(),
                                lastSendTime
                        ));
                        sysMsg.setStatus("0");
                        sysMsg.setSendTime(new Date());
                        sysMsg.setSenderId(1L);
                        sysMsg.setReceiverId(sysUser.getUserId());
                        sysMsgService.insertSysMsg(sysMsg);
                    }

                    SysMsg sysMsg = new SysMsg();
                    sysMsg.setType("2");
                    sysMsg.setTitle(String.format("%s 设备离线了,识别码:%s", stsDevice.getName(), stsDevice.getIdCode()));
                    sysMsg.setContent(String.format("场所：%s，设备：%s，识别码：%s，超过了1小时未收到数据上传，上一次上传时间在：%s",
                            stsDevice.getDeptName2(), stsDevice.getName(), stsDevice.getIdCode(),
                            lastSendTime
                    ));
                    sysMsg.setStatus("0");
                    sysMsg.setSendTime(new Date());
                    sysMsg.setSenderId(1L);
                    sysMsg.setReceiverId(1L);
                    sysMsgService.insertSysMsg(sysMsg);

                    stsDevice.setStatus("1");
                    stsDeviceService.updateStsDevice(stsDevice);
                }

            }catch (Exception e){
                log.error(e.getMessage(), e);
            }
        }

    }
}
